<template>
  <base-breadcrumb>
    <a-spin :spinning="progressing" :tip="tips">
    <a-form-model :model="form" ref="ruleForm" :rules="rules">
      <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
        <div style="display:flex;justify-content: space-between">
          <div class="titleName"> 基本信息</div>
          <div style="float:right">
            <a-button class="button" :disabled="type=='view' || type=='approve' || loading" @click="preSave"
                      type="primary">保存草稿
            </a-button>
            <a-button class="button" :disabled="type=='view' || type=='approve' || loading || !planId" type="primary"
                      @click="submitReview">提交
            </a-button>
            <a-button class="button" @click="goBack()" type="default">关闭</a-button>
          </div>
          <!-- <title-name title="基本信息"></title-name> -->
        </div>
        <div>
            <a-tabs ref="tabs" v-model="currentStep" @change="callback">
              <a-tab-pane :key="1" tab="基本信息">
                <title-name title="新增施工进度总计划调整"></title-name>
                <a-row :gutter="24">
                  <a-col :md="8" :sm="8">
                    <a-form-model-item label="分公司"
                                       :labelCol="{lg: {span: 6}, sm: {span:6}}"
                                       :wrapperCol="{lg: {span: 18}, sm: {span: 18} }" prop="branchId">
                      <SelectSubCompany placeholder="请选择" v-model="form.branchId" @change="changeCompany"
                                        :disabled="type=='view'|| type=='approve' || type=='edit'"></SelectSubCompany>
                    </a-form-model-item>
                  </a-col>
                  <a-col :md="8" :sm="8">
                    <a-form-model-item label="项目名称"
                                       :labelCol="{lg: {span: 6}, sm: {span:6}}"
                                       :wrapperCol="{lg: {span: 18}, sm: {span: 18} }" prop="projectId">
                      <!-- <SelectProject :ifMasterPlanAdjust="true" placeholder="请选择" v-model="form.projectId" :isClear="false" :disabled="type=='view'"
                                     :form="form" keyValue="branchId"></SelectProject> -->
                      <a-select @focus="getAuditProject" v-model="form.projectId"
                                :disabled="type=='view' || type=='approve' || type=='edit'">
                        <a-spin v-if="loading" slot="notFoundContent" size="small" />
                        <a-select-option v-for="item in projectLists" :key="item.projectId" :value="item.projectId">
                          {{ item.projectName }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>

                  <a-col :md="8" :sm="8">
                    <a-form-model-item label="调整原因"
                                       :labelCol="{lg: {span: 6}, sm: {span:6}}"
                                       :wrapperCol="{lg: {span: 18}, sm: {span: 18} }" prop="adjustReasonCode">
                      <a-select :getPopupContainer="getPopupContainer" :disabled="type=='view' || type=='approve' "
                                v-model="form.adjustReasonCode">
                        <a-spin v-if="loading" slot="notFoundContent" size="small" />
                        <a-select-option v-for="item in reasonList" :key="item.id" :value="item.id">{{ item.name }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                  <a-col :md="8" :sm="8">
                    <a-form-model-item label="调整最高节点等级"
                                       :labelCol="{lg: {span: 6}, sm: {span:6}}"
                                       :wrapperCol="{lg: {span: 18}, sm: {span: 18} }">
                      <BaseInput disabled v-model="form.maxAdjustLevel"></BaseInput>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row :gutter="24">
                  <a-col :md="24" :sm="24">
                    <a-form-model-item label="情况说明" style="margin-top:20px;padding-right:20px"
                                       :labelCol="{lg: {span: 2}, sm: {span:2}}"
                                       :wrapperCol="{lg: {span: 22}, sm: {span: 22} }" prop="information">
                      <BaseTextarea
                        :disabled="type=='view' || type=='approve'"
                        :maxLength="300"
                        placeholder="请输入说明情况"
                        v-model="form.information">
                      </BaseTextarea>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-button style="float:right;" @click="nextStep()" type="primary">下一步</a-button>
              </a-tab-pane>

              <a-tab-pane :key="2" tab="预调整">
                <pre-adjust :adjustPlanId="adjustPlanId" />

                <a-button style="float:right;" @click="nextStep()" type="primary">下一步</a-button>
              </a-tab-pane>

              <a-tab-pane :key="3" tab="附件上传">

                <title-name title="附件上传"></title-name>
                <u-table
                  :disabled="type=='view'"
                  :listUrl="listUrl"
                  :uploadList="uploadList"
                  :isShow="isShow"
                  :deleteUrl="deleteUrl"
                  :reqMethod="reqMethod"
                  :businessId="businessId"
                  businessCode="PM07"></u-table>
              </a-tab-pane>
            </a-tabs>
        </div>
      </a-card>

      <div style="float:right;margin-top: 20px;margin-bottom: 20px;">
      </div>
    </a-form-model>
    </a-spin>
  </base-breadcrumb>
</template>

<script>
import { getAttachment } from '@/api/commons'
import { STable, Ellipsis } from '@/components'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/SelectProjects/SelectProject' // 项目
import { deleteTeamList } from '@/api/subcontractors/labour'
import PreAdjust from '../../gantt/preAdjust'
import {
  getBasic,
  getPreAdjustFiles,
  addBasicInformatin,
  getReasonList,
  getBasicInformatin,
  submitReview
} from '@/api/adjust'
import TrendVue from '@/components/Trend/Trend.vue'
import { getAuditProject } from '@/api/themeChoose/themeChoose'

const columns = [
  {
    title: '序号',
    width: 65,
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '推荐分包商名称',
    dataIndex: 'recommendSubcontractors'
  },
  {
    title: '推荐人',
    dataIndex: 'recommend'
  },
  {
    title: '分公司',
    dataIndex: 'branchCompany'
  },
  {
    title: '推荐项目',
    dataIndex: 'recommendProject'
  },
  {
    title: '合作事项',
    dataIndex: 'cooperation'
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]
const columns1 = [
  {
    title: '序号',
    dataIndex: 'name',
    width: '10%',
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '附件名称',
    dataIndex: 'annuxName',
    width: '15%',
    scopedSlots: { customRender: 'age' }
  },
  {
    title: '附件格式',
    dataIndex: 'annux',
    scopedSlots: { customRender: 'annux' }
  },
  {
    title: '附件地址',
    dataIndex: 'annuxAddress',
    width: '40%',
    scopedSlots: { customRender: 'annuxAddress' }
  },
  {
    title: '操作',
    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' }
  }
]


// 数组创建时候的下标
var numbe = 0

export default {
  name: 'StandardList',
  components: {
    STable,
    PreAdjust,
    SelectSubCompany,
    SelectProject
  },
  props: {
    text: String
  },

  data() {
    this.columns1 = columns1
    return {
      tips:'',
      isShow: true, // 查看、审批不显示上传按钮
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getGroup(requestParameters)
          .then(res => {
            return res.data
          })
      },
      visible: false,
      currentStep: 1,
      preStep:1,
      subcontractorName: '',
      planId: '',
      adjustPlanId: '',
      mostNodeLevel: '',
      projectLists: [],
      subcontractorId: 1,
      selectDatas: {}, //

      // 附件上传
      listUrl: '/cscec-project-business/file/constrction-progress/plan-adjust/queryFile',
      deleteUrl: '/cscec-project-business/file/constrction-progress/plan-adjust/deleteFile',
      uploadList: '/cscec-project-business/file/constrction-progress/plan-adjust/uploadFile',
      businessId: '',
      reqMethod: 'post',
      type: '',
      columns,
      columns1,
      editingKey: '',
      title: '',
      selectedRowKeys: [],
      fileList: [
        {
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
        }
      ],

      headers: {
        authorization: 'authorization-text'
      },
      form: {
        investigateType: ''
      },
      status: 'all',
      areaCode: '',
      basicList: {},
      progressing: false,
      loading: false,
      dataList: [],
      id: '',    // 项目id
      designTypes: [],
      reasonList: [],
      adjustReasonCode: '',
      isCompany: false,
      isManager: false,
      selectedRows: [],
      information: '',
      rules: {
        adjustReasonCode: [{ required: true, message: '请选择调整原因', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        branchId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        information: [{ required: true, message: '请输入情况说明', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.planId = this.$route.query.id
    this.businessId = this.planId
    this.type = this.$route.query.type
    if (this.type == 'view' || this.type == 'approve') {
      this.isShow = false
    } else {
      this.isShow = true
    }
    this.getReasonList()
    this.getBasicInformatin()
    // this.$refs.tabs.key = this.currentStep

  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows,   // 当前行所有数据
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    preSave() {
      if (this.currentStep === 1) {
        if (!this.form.projectId && !this.form.adjustReasonCode && !this.form.information) {
          this.$message.error('请先填写基本信息')
          return
        }
        this.form.id = this.planId
        this.tips = '基本信息保存中...'
        this.progressing = true
        addBasicInformatin(this.form).then((res) => {
          this.progressing = false
            this.$message.success('保存草稿成功')
            if(!this.planId){
              this.adjustPlanId = res.data.message
              this.planId = this.adjustPlanId
            }
        }).catch(()=>{
          this.progressing = false
        })
      } else {
        this.$message.success('保存成功')
        this.$router.push('/project/adjust')
      }
    },
    submitReview() {
      if (this.loading) return
      this.loading = true
      let _this = this
      this.$confirm({
        title: '警告提醒！',
        content: '是否提交当前数据？',
        okType: 'danger',
        onOk() {
          _this.tips = '提交中...'
          _this.progressing = true
          return new Promise((resolve,rej)=>{
            submitReview({ id: _this.planId }).then((res) => {
              if (res.code === 200) {
                _this.loading = false
                _this.progressing = false
                _this.$router.push('/project/adjust')
                _this.$message.success('提交成功')
              }
              return resolve()
            }).catch(() => {
              _this.loading = false
              _this.progressing = false
              return rej()
            })
          });
        },
        onCancel() {
          _this.loading = false
          _this.progressing = false
        }
      })
      // submitReview({id:this.planId}).then(res=>{
      //   this.loading=false
      //   if(res.code=='200'){
      //     this.$router.push("/project/adjust")
      //     this.$message.success("提交成功")
      //   }
      // }).catch(() => {
      //   this.loading=false
      // })
    },
    getPopupContainer(triggerNode) {
      return triggerNode.parentNode
    },
    getBasicInformatin(call) {
      if (this.planId) {
        this.progressing = true
        this.tips = '基本信息获取中...'
        getBasicInformatin({ planId: this.planId }).then(res => {
          this.form = res.data
          this.projectLists.push({
            projectId: res.data.projectId,
            projectName: res.data.projectName
          })
          this.progressing = false
          if(call){
            call()
          }
        })
      }
    },
    getAuditProject() {
      this.loading = true
      getAuditProject({
        ifMasterPlanAdjust: 0,
        branchComIds: [this.form.branchId],
        auditStatus: 2,
        masterPlanStatus: 2
      }).then(res => {
        this.projectLists = res.data
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    getReasonList() {
      this.loading = true
      getReasonList({ type: '12' }).then(res => {
        this.reasonList = res.data
        this.loading = false
      })
    },
    goBack() {
      this.form = {}
      this.$multiTab.close(this.$route.fullpath)
    },
    onChange(value) {
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    employeeNums(val) {
      this.employeeNum = val
    },
    handleSave(e) {  //
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.form.validateFields((err, values) => {
            if (!err) {
            }
          })
        }
      })
    },
    changeCompany(value) {
      this.$set(this.form, 'projectId', '')
    },
    callback(key) {   // tabs切换
      const preStep = this.preStep
      const currentStep = this.currentStep
      if (preStep === 1) {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            if (!this.form.projectId && !this.form.adjustReasonCode && !this.form.information) {
              this.$message.error('请先填写基本信息')
              return
            }
            if (this.type != 'view') {
              this.progressing = true
              this.tips = '基本信息保存中...'
              this.form.id = this.planId
              this.currentStep = 1
              addBasicInformatin(this.form).then((res) => {
                if(!this.planId){
                  this.adjustPlanId = res.data.message
                  this.planId = this.adjustPlanId
                  if (this.type === 'add') {
                    this.businessId = res.data.message
                  }
                }
                this.type = 'edit'
                this.progressing = false
                this.preStep = currentStep
                this.currentStep = key
              }).catch(()=>{
                this.progressing = false
              })
            }
          }else{
            this.$message.warning("请填写完所有必填项信息")
            this.currentStep = 1
          }
        })
      }else{
        this.preStep = currentStep
      }
    },
    handleCancel() {
      let _this = this
      _this.visible = false
      const form = _this.$refs.createModal.form
      form.resetFields() // 清理表单数据
    },
    handleOk() {
      let _this = this
      //console.log(_this.selectedRows)
      if (_this.selectedRows.length == 1) {
        _this.form.subcontractorName = _this.selectedRows[0].recommendSubcontractors
        _this.visible = false
      } else if (_this.selectedRows.length > 1) {
        this.$message.warning('请选择一家分包商')
      } else {
        return false
      }
      // const form = this.$refs.createModal.form
      // this.confirmLoading = true
      // form.validateFields((errors, values) => {
      //   if (!errors) {
      //     //console.log('values', values)
      //
      //     values.projectId = localStorage.getItem("projectId")
      //     values.projectJobId = this.mdl.jobId
      //     values.employeeNum = this.employeeNum
      //   }
      // })
    },
    nextStep() {
      // 下一步
      let preStep = this.currentStep
      if(this.type==='view'){
        if (this.currentStep === 3) {
          return
        }
        this.preStep = preStep
        this.currentStep++
        return
      }
      if (preStep === 1) {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            if (!this.form.projectId && !this.form.adjustReasonCode && !this.form.information) {
              this.$message.error('请先填写基本信息')
              return
            }
            this.form.id = this.planId
            this.tips = '基本信息保存中...'
            this.progressing = true
            this.currentStep = 1
            addBasicInformatin(this.form).then((res) => {
              this.progressing = false
              // if(res.code=='200'){
              this.currentStep = 2
              this.preStep = preStep
              if(!this.planId){
                this.adjustPlanId = res.data.message
                this.planId = this.adjustPlanId
                if (this.type === 'add') {
                  this.businessId = res.data.message
                }
              }
              this.type = 'edit'
              // }
            }).catch(()=>{
              this.progressing = false
            })
          } else {
            this.$message.warning("请填写完所有必填项信息")
          }
        })
      }else{
        if (this.currentStep === 3) {
          return
        }
        this.preStep = preStep
        this.currentStep++
      }
    },


    // 上传
    handleChanges(info) {
      getAttachment({ multipartFile: info.file, projectId: 1 }).then(res => {
        //console.log('上传事件如下：', res)
      })
    }


  }
}
</script>

<style scoped>
.wrapper-row {
  padding-left: 55px;
  font-weight: bold;
  letter-spacing: 1px;
}

/deep/ .ant-form-item label {
  font-size: 12px;
}

/deep/ .ant-btn {
  border-radius: 5px;
}

/deep/ .ant-calendar-picker-input.ant-input {
  width: 100%;
}

/deep/ .ant-input {
  /*width: 70%;*/
  border-radius: 5px;
}


/deep/ .ant-card.ant-card-bordered {
  border-radius: 5px;
}

.ant-avatar-lg {
  width: 48px;
  height: 48px;
  line-height: 48px;
}


.title-name {
  border-left: 5px solid #1890ff;
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 20px;
  padding-left: 15px;
  height: 20px;
  line-height: 20px;
}

/deep/ .table-page-search-wrapper .ant-form-inline .ant-row .ant-col.ant-col-sm-24.ant-col-md-12 {
  padding-left: 80px;
}

/*/deep/ .ant-layout, .ant-layout{*/
/*  padding:0*/
/*}*/
.button {
  margin: 0 10px;
}

/deep/ .ant-card-bordered {
  /* margin-top:60px */
}

/deep/ .ant-table-pagination.ant-pagination {
  display: none
}

/deep/ form .ant-mentions, form textarea.ant-input {
  width: 100%;
  height: 110px !important
}

.titleName {
  border-left: 5px solid #1890ff;
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 20px;
  padding-left: 15px;
  height: 20px;
  line-height: 20px;
  margin-left: 0;
}

</style>

